package com.example.dangerouscargodriver.controller;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

public abstract class Controller {

    private LooperThread mLooperThread = null;
    private WorkHandler mHandler = null;

    public Controller(){
        mLooperThread = new LooperThread();
        mLooperThread.start();
        while(mLooperThread.getLooper() == null){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        mHandler = new WorkHandler(mLooperThread.getLooper());
    }

    public void sendMessage(Message msg) {
        mHandler.sendMessage(msg);
    }

    public void sendEmptyMessage(int what) {
        mHandler.sendEmptyMessage(what);
    }

    public void sendMessageDelayed(Message msg, long delayMillis){
        mHandler.sendMessageDelayed(msg, delayMillis);
    }

    protected abstract void handleControllerMessage(Message msg);

    class LooperThread extends Thread {
        private static final String TAG = "LooperThread";
        private Looper mLooper = null;

        public Looper getLooper(){
            return mLooper;
        }

        @Override
        public void run() {
            Looper.prepare();
            mLooper = Looper.myLooper();
            Looper.loop();
        }
    }

    public class WorkHandler extends Handler {
        private static final String TAG = "WorkHandler";

        public WorkHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handleControllerMessage(msg);
        }
    }
}
